/**
 * @file 工单操作-核配件
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'laytpl', 'table', 'NP', 'zmnUtils', '$http', 'upload'], function (exports) {

        var $ = layui.$;
        var form = layui.form;
        var laytpl = layui.laytpl;
        var table = layui.table;
        var opCommonUtils = layui.list_modify_common;
        let upload = layui.upload;
        let timestamp = new Date().getTime();

        var $http = layui.$http;
        var zmnUtils = layui.zmnUtils;
        var NP = layui.NP;

        var tableData = {};//后台传来的初始数据
        var master = {};//工程师信息

        var layerOpen = {//打开工程师配件弹窗的序列,关闭弹窗要用
            innerPurchase: function () {
                var index = this.baseLayerOpen("内采/网购配件");
                return index;
            },
            baseLayerOpen: function (title) {
                return layer.open({
                    type: 1,
                    title: title,
                    area: ["1200px", "600px"],
                    content: $("#view"),
                    zIndex:2000,
                    cancel: function () {
                        $("#view").empty();
                    }
                })
            }
        }

        /**
         * 初始后台基础数据,
         * 如果有使用配件,则配件列表中不在渲染使用过的配件
         */
        function formatData() {
            for (var i = 0, len = partsList.length; i < len; i++) {
                //工程师配件列表 left是没使用,right是使用
                tableData['left' + partsList[i].masterId] = [];
                tableData['right' + partsList[i].masterId] = [];//使用配件 展示

                var ele = "#" + partsList[i].masterId;//总金额元素id

                for (var j = 0; j < partsList[i].partMasterDetailVOList.length; j++) {
                    //如果工程师有使用配件
                    if ( +partsList[i].partMasterDetailVOList[j].useNumber > 0) {
                        //如果有使用配件 ,初始页面checked使用配件按钮;
                        form.render();
                        //将使用了的配件加入使用列表
                        tableData['right' + partsList[i].masterId].push(partsList[i].partMasterDetailVOList[j]);
                        //隐藏当前编辑按钮
                        $(ele).hide();
                    }else{
                        tableData['left' + partsList[i].masterId].push(partsList[i].partMasterDetailVOList[j]);
                    }
                }
                //使用过的配件总金额
                var count = sumOfParts(tableData['right' + partsList[i].masterId]);
                $(ele).siblings().find(".sum-item-1").text(zmnUtils.unit.fenToYuan(count));
                renderTable({
                    elem: '#inner-purchase-table' + partsList[i].masterId,
                    defaultData: {
                        masterId: partsList[i].masterId,
                        mastername: partsList[i].masterName,
                    },
                    data: tableData['right' + partsList[i].masterId]
                });
                //表格中的编辑按钮
                table.on('toolbar(inner-purchase-table' + partsList[i].masterId + ')', function (obj) {
                    var setData = obj.config.defaultData;
                    var opt = {
                        index: layerOpen.innerPurchase(),
                        currentBtnId: setData.masterId,
                        currentMasterName: setData.mastername
                    }
                    //打开配件弹窗,并渲染当前工程师的基础数据
                    openLayerFrame(opt);
                    return false;
                });
            }
        }

        /**
         * 打开配件列表
         */
        function openPartsList() {
            var res = {
                name: "配件列表",
            };
            var tpl = $("#tpl-list").html();
            laytpl(tpl).render(res, function (htm) {
                $("#view").removeClass("d-hide");
                $("#view").html(htm);
            });
        }

        /**
         * 如果arr中包含data对象,则删除相同项,如果没有则不管;
         * arr与data包含字段必须一样;
         * @param arr {array}
         * @param data {object}
         */
        function eachArrayDeleteData(arr, data) {
            for (var i = 0; i < arr.length; i++) {
                var arr_str = arr[i].drawId + arr[i].partId;
                var data_str = data.drawId + data.partId;
                if (arr_str.indexOf(data_str) != -1) {
                    arr.splice(i, 1);
                }
            }
        }

        /**
         * 渲染未使用配件列表
         * @param arr {array} 未使用配件数据
         * @returns {*}
         */
        function renderLeft(arr) {
            return table.render({//配件列表
                elem: '#table-left',
                height: 300,
                limit: arr.length,
                cols: [
                    [
                        {field: 'drawId', hide: true},
                        {field: "partFullName", title: '配件名称'},
                        {field: "drawTime", title: "领取时间"},
                        {field: "remainingNumber", title: "剩余数量"},
                    ]
                ],
                data: arr
            });
        }

        /**
         * 渲染已使用配件列表
         * @param arr {array} 已使用配件数据
         * @returns {*}
         */
        function renderRight(arr) {
            table.render({//使用配件清单
                elem: '#table-right',
                height: 300,
                limit: arr.length,
                cols: [
                    [
                        {field: 'drawId', hide: true},
                        {field: 'partId', hide: true},
                        {field: 'decimalDigit', hide: true},
                        {field: "partFullName", title: '配件名称'},
                        {field: "drawTime", title: "领取时间"},
                        {field: "price", title: "配件销售单价", templet: '#price'},
                        {field: "unit", title: "单位"},
                        {field: "remainingNumber", title: "剩余数量", templet: function (rowData) {
                            return accSub(rowData.totalNumber, rowData.useNumber);
                            //return NP.minus(rowData.totalNumber, rowData.useNumber);
                        }},
                        {field: "useNumber", title: "使用数量(可编辑)",width:50, edit: 'text', event: "edit", templet: function (rowData) {
                            var useNumber = 0;

                            if(rowData.totalNumber - rowData.useNumber >= 0) {
                                useNumber = rowData.useNumber;
                            }

                            return `<p class="">${ useNumber }</p>`;
                        }},
                        {
                            field: "comparisonImgSrc", title: "新旧配件对比", width: 170, templet: function (rowData) {
                                // 新旧配件照片非必传时，不显示照片上传组件
                                if (rowData.needImg == 2) {
                                    return `
                                    <div class="layui-upload-drag" id="part-add-` + rowData.partId + `" class="part-add">
                                        <img src="` + rowData.comparisonImgSrc + `" id="part-add-` + rowData.partId + `-values" style="display: none">
                                        <input type="hidden" id="part-add-` + rowData.partId + `-value" name="part-add-` + rowData.partId + `" value="` + rowData.comparisonImgSrc + `">
                                        <i class="layui-icon"></i>
                                        <p>点击上传</p>
                                    </div>
                                    <div class="layui-inline btn-img">
                                        <i class="layui-icon layui-icon-search btn-review"></i><br>
                                        <i class="layui-icon layui-icon-delete btn-delete"></i>
                                    </div>`;
                                }
                                return '';
                            }
                        },
                    ]
                ],
                data: arr,
            });
            for (let i = 0; i < arr.length; i++) {
                let elemId = "part-add-" + arr[i].partId;
                let valueId = "part-add-" + arr[i].partId+ "-value";
                uploaderImage(elemId, valueId, arr[i]);
                let url = arr[i].comparisonImgSrc;
                if (url) {
                    reLoadImage(elemId, url, valueId);
                }
            }
        }

        /**
         * 初始化配件表格
         * @param opt {object} 左边数据,和右边空数组
         */
        function initTable(opt) {
            renderLeft(opt.data_left);//未使用配件列表;
            renderRight(opt.data_right);//已使用配件列表;
            table.on("rowDouble(table-left)", function (obj) {//添加配件
                var data = obj.data;
                //添加到右边使用列表
                opt.data_right.unshift(data);
                //从未使用列表中去掉选中项
                obj.del();
                eachArrayDeleteData(opt.data_left, data);
                // 刷新使用列表
                renderRight(opt.data_right)
            });

            table.on("rowDouble(table-right)", function (obj) {//删除配件
                var data = obj.data;
                data.remainingNumber = data.totalNumber;
                data.useNumber = 0;
                //添加到左边未使用列表
                 opt.data_left.unshift(data);
                //从使用列表中去掉选中项
                obj.del();
                eachArrayDeleteData(opt.data_right, data);
                //是否停留在模糊查询
                var partsName = $(".d-filter").val();
                if (partsName) {
                    vagueQuery(partsName, opt.data_left);
                }
                //刷新未使用列表
                renderLeft(opt.data_left);
            });

            table.on('tool(table-right)', function(obj){
                var rowData = obj.data;
                if(obj.event === 'edit') {
                    var $input = obj.tr.find('td[data-field="useNumber"] input');
                    var decimalDigit = rowData.decimalDigit;
                    if (decimalDigit == 0){
                        $input.on('input', function () {
                            var $this = $(this);
                            $this.val($this.val().replace(/[^\d]/ig, '')
                                .replace(/\-{1,}/g,''));
                        });
                    }else if (decimalDigit == 1){
                        $input.on('input', function () {
                            var $this = $(this);
                            var value = $this.val()
                                .replace(/\-{1,}/g,'')
                                .replace(/[^\d.-]/g, '')
                                .replace(/^\./g, '')
                                .replace(/\.{2,}/g, '.')
                                .replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
                                .replace(/^(\d+)\.(\d).*$/, '$1.$2');

                            $this.val(value);
                        });
                    } else if (decimalDigit == 2){
                        $input.on('input', function () {
                            var $this = $(this);
                            var value = $this.val()
                                .replace(/\-{1,}/g,'')
                                .replace(/[^\d.-]/g, '')
                                .replace(/^\./g, '')
                                .replace(/\.{2,}/g, '.')
                                .replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
                                .replace(/^(\d+)\.(\d\d).*$/, '$1.$2');

                            $this.val(value);
                        });
                    } else {
                        layer.msg("小数位数异常");
                    }
                }
            });

            // 使用数量
            table.on("edit(table-right)", function (obj) {
                var value = obj.value;
               if(obj.data.totalNumber - value < 0 ){//输入数量比剩余数量多
                    obj.update({
                        useNumber: obj.data.totalNumber,
                    });
                    obj.data.useNumber = 0;
                    layer.msg("剩余配件不足");
                }
                //重新渲染
                renderRight(opt.data_right);
            });
            initClickEvent();
        }

        /**
         * 输入框的模糊查询
         * @param val {string} 需要查询的字符串
         * @param arr {array} 需要遍历的数组
         */
        function vagueQuery(val, arr) {
            var data = [];
            var reg = new RegExp(val, "i");
            if (val == '') {
                renderLeft(arr);
                return;
            }
            for (var i = 0; i < arr.length; i++) {
                if (reg.test(arr[i].partFullName)) {
                    data.push(arr[i]);
                }
            }
            renderLeft(data);
        }

        /**
         * 监听配件名称输入框,渲染table匹配数据
         */
        function listenFilter(arr) {
            //监听配件名称输入框 模糊查询
            $(".d-filter").on("keyup", function (event) {
                var val = event.currentTarget.value;
                //模糊查询
                vagueQuery(val, arr);
            })
        }

        /**
         * 是否使用配件
         * @returns {boolean}
         */
        function isUseParts() {
            var isUse = $(".useparts").prop("checked");
            if (isUse) {
                $('.is-use-parts').show();
                $('.no-use-parts').hide();
                form.render();
                return;
            }
            $('.is-use-parts').hide();
            $('.no-use-parts').show();
            form.render();
            return;
        }

        /**
         * 渲染确定后的使用配件清单
         * @param opt{object} {elem,defaultData{
         *     masterId,mastername
         * },data}等数据
         */
        function renderTable(opt) {
            if (opt.data.length < 1) {
                $(opt.elem).siblings(".layui-table-view").css("display", "none");
                $(opt.elem).parent().siblings().find(".sum-item").hide();
                return
            }
            $(opt.elem).siblings(".layui-table-view").css("display", "block");
            $(opt.elem).parent().siblings().find(".sum-item").show();

            table.render({
                elem: opt.elem,
                defaultToolbar: [],
                toolbar: "#headbar",
                defaultData: opt.defaultData,
                cols: [
                    [
                        {field: "partFullName", title: '配件名称'},
                        {field: "drawTime", title: "领取时间"},
                        {field: "price", title: "配件销售单价", templet: '#price'},
                        {field: "unit", title: "单位"},
                        {field: "useNumber", title: "使用数量"},
                        {field: "remainingNumber", title: "剩余数量"},
                        {field: "comparisonImgSrc", title: "新旧配件对比", width:170, templet: function (rowData) {
                                return `<div class="layui-upload-drag" id="part-main-add-`+ rowData.partId +`" class="part-add">
                                <img src="`+ rowData.comparisonImgSrc +`" id="part-main-add-`+ rowData.partId +`-values" style="display: none">
                                <input type="hidden" id="part-main-add-`+ rowData.partId +`-value" name="part-main-add-`+ rowData.partId +`" value="`+ rowData.comparisonImgSrc +`">
                                <i class="layui-icon"></i>
                                <p>点击上传</p>
                            </div>
                            <div class="layui-inline btn-img">
                                <i class="layui-icon layui-icon-search btn-main-review"></i><br>
                            </div>`;
                            }},
                    ]
                ],
                data: opt.data
            });

            let arr = opt.data;

            for (let i = 0; i < arr.length; i++) {
                let elemId = "part-main-add-" + arr[i].partId;
                let valueId = "part-main-add-" + arr[i].partId+ "-value";
                let url = arr[i].comparisonImgSrc;
                if (url) {
                    reLoadImage(elemId, url, valueId);
                }
            }

            initViewEvent();
        }

        /**
         * 已使用配件清单价格 求和
         * @param arr{array} 确定的配件清单
         * @param ele {string} 填充总额的元素
         */
        function sumOfParts(arr) {
            var sum = 0;

            if (arr && arr.length) {
                sum = arr.reduce(function (acc, curr) {
                    var price = curr.price;
                    var num = curr.useNumber;
                    //var total = NP.times(price, num);
                    var total = parseInt(accMul(price, num));
                    curr['inPartAmount'] = total;
                    return NP.plus(acc, total);
                }, 0);
            }

            return sum;
        }

    /**
     * 减法函数，用来得到精确的减法结果
     * @param {Object} arg1
     * @param {Object} arg2
     */
    function accSub(arg1, arg2) {
        var r1 = deal(arg1);
        var r2 = deal(arg2);
        var m = Math.pow(10, Math.max(r1, r2));
        //动态控制精度长度
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n)
    }

    /**
     * 乘法函数，用来得到精确的乘法结果
     * @param {Object} arg1
     * @param {Object} arg2
     */
    function accMul(arg1, arg2) {
        var m = 0;
        m += deal(arg1);
        m += deal(arg2);
        var r1 = Number(arg1.toString().replace(".", ""));
        var r2 = Number(arg2.toString().replace(".", ""));
        return (r1 * r2) / Math.pow(10, m)
    }

    /**
     * 求小数点后的数据长度
     */
    function deal(arg) {
        var t = 0;
        try {
            t = arg.toString().split(".")[1].length
        } catch(e) {}
        return t;
    }

        /**
         * 初始化页面
         */
        function initPage() {
            //处理后台传输数据
            formatData();
            let tableView = $('.table-render tbody').length;
            if(tableView > 0){
                $('.useparts').prop('checked',true);
                $('.nouseparts').prop('chedked',false);
            }else {
                $('.useparts').prop('checked',false);
                $('.nouseparts').prop('checked',true);
            }
            form.render();
            //是否使用配件
            isUseParts();


        }


        /**
         *打开配件弹窗,并渲染当前工程师的基础数据
         * @param opt {object} 需要index(关闭弹出配件层索引)
         *                     ,currentBtnId(当前点击的按钮唯一id,此处用的工程师id,)
         *                     ,currentMasterName(当前选中工程师的名字)
         */
        function openLayerFrame(opt) {
            //打开配件列表模板
            openPartsList();
            var index = opt.index;
            var currentBtnId = opt.currentBtnId;
            var currentMasterName = opt.currentMasterName;
            $(".index").attr({
                "data-index": index,
                "data-masterId": currentBtnId,
                "data-mastername": currentMasterName
            });
            initTable({
                data_left: tableData['left' + currentBtnId],
                data_right: tableData['right' + currentBtnId]
            });
            //配件输入框
            listenFilter(tableData['left' + currentBtnId]);
        }

        /**
         * 初始化页面事件
         */
        function initEvent() {

            /**
             * 内采网购
             */
            $(".d-edit").on("click", function (event) {
                var opt = {
                    index: layerOpen.innerPurchase(),//关闭层用
                    currentBtnId: $(this).attr("id"),//获取工程师当前工程师Id
                    currentMasterName: $(this).attr("data-mastername"),//当前工程师的名字
                };
                openLayerFrame(opt);
            });

            /**
             * 确认使用配件列表
             */
            form.on("submit(btn-list)", function (data) {
                var index = +($(".index").attr("data-index"));
                var masterId = +($(".index").attr("data-masterId"));
                var currentMasterName = $(".index").attr("data-mastername");

                var partsList = tableData['right' + masterId] || [];
                // 单位转换
                //partsList = unitConvertorForSave(partsList);

                let canSubmit = true;
                $(".right img").each(function (index, ele) {
                    console.log("index：", index, "ele：", ele)
                    let imgUrl = $(this).next().val();
                    if (!imgUrl) {
                        let partName = $(this).parents("tr").find('td').eq(3).children().eq(0).html();
                        layer.msg("请先上传"+ partName +",新旧配件对比照");
                        canSubmit = false;
                        return false;
                    }
                });
                if (!canSubmit) {
                    return false;
                }
                for(j = 0; j < partsList.length; j++) {
                    let partData = partsList[j];
                    // 当是需要上传新旧配件照的时候 但是没上传，就弹出提示框
                    if (partData.needImg == 2 && !partData.comparisonImgSrc) {
                        layer.msg("请先上传"+ partsList[j].partFullName +",新旧配件对比照");
                        return false;
                    }
                }

                layer.close(index);//关闭
                $("#view").empty();//清空

                //配件和
                var count = sumOfParts(partsList);

                var ele = "#" + masterId;
                $(ele).siblings().find(".sum-item-1").text(
                    zmnUtils.unit.fenToYuan(count)
                );
                //工程师配件列表
                master.inPartAmount = count;
                master.typeName = "内采";
                master.masterId = masterId;
                master.masterName = currentMasterName;
                master.partMasterDetailDTOList = partsList;

                var list = {};
                list.orderId = $("input[name=orderId]").val();
                list.workId = $("input[name=workId]").val();
                list.partMasterDTOList = Array(master);
                //used =2:使用配件;=1:没有使用配件
                list.used = 2;

                // 先做指标校验，然后再保存配件
                var url = '/work/modify/check/indicators.action';
                $http.lockSave(url, list, data.elem).then(function (data) {
                    var msg = '';
                    if (!data) {
                       savePart(list);
                       return;
                    }else {
                        msg = data;
                    }

                    layer.msg(msg, {icon: 1, time: 1000}, function () {
                        opCommonUtils.goOperateHome();
                    });
                }, (msg) => {
                    if(msg.localeCompare("工单配件平均费用过高") == 0) {
                        layer.confirm('工单配件平均费用过高，确定继续保存吗？', {
                            btn: ['确定','取消']
                        },function () {
                            savePart(list);
                        });
                    } else {
                        layer.msg(msg);
                    }
                });

                function savePart(list) {
                    var url = '/work/modify/save/part.action';
                    $http.lockSave(url, list, data.elem).then(function (data) {
                        var msg = '';
                        if (!data) {
                            msg = '操作成功';
                        } else {
                            msg = data;
                        }

                        layer.msg(msg, { icon: 1, time: 1000 }, function () {
                            opCommonUtils.goOperateHome();
                        });
                    }, (msg) => {
                        layer.msg(msg);
                    });
                }

                return false;
            });
            /**
             * 是否使用配件
             */
            $(".is-use-parts-item").on("click", function () {
                isUseParts();
            });
            //未使用配件
            form.on("submit(confirm)", function (data) {
                let isUsedPart = false;//是否使用配件,有使用配件就弹出提示,没有就不用弹出提示;
                let tableRender = $('.table-render');
                tableRender.each(function (k,v){
                    let layuiTableView = $(this).find('.layui-table-view');
                    if(layuiTableView.length > 0){
                        isUsedPart = true;
                    }
                });
                let list = data.field;
                function transportData(){
                    list.partMasterDTOList = [];

                    var url = '/work/modify/save/part.action';
                    $http.lockSave(url, list, data.elem).then(function (data) {
                        var msg = '';
                        if (!data) {
                            msg = '操作成功';
                        }else {
                            msg = data;
                        }
                        layer.msg(msg, { icon: 1, time: 1000 }, function () {
                            opCommonUtils.goOperateHome();
                        });
                        }, (msg) => {
                            layer.msg(msg);
                    });

                }
                if (isUsedPart) {
                    layer.confirm('未用配件，将清空内采、外报、订单杂项费用，确认？', {
                        btn: ['确定']
                    }, transportData);
                }else{
                    transportData();
                }
                return false
            });
        }

    /**
     * 描述: 图片上传方法
     * @param elemId
     * @param valueId
     */
    let indexUploadImags;

    function uploaderImage(elemId, valueId, rowData) {
        upload.render({
            elem: '#' + elemId
            , exts: 'jpg|png|jpeg'
            , acceptMime: 'image/*'
            , accept: 'images'
            , url: '/work/modify/uploader/orderPartComparisonPhoto?timestamp=' + timestamp + '&elemId=' + elemId
            , size: 5120
            , beforeSend: function (obj) {
                indexUploadImags = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            }
            , done: function (res) {
                if (res.statusBool) {
                    let data = res.data;
                    $("#" + valueId).val(data);
                    $("#" + valueId+"s").attr("src",data).attr("style", "width: 0;height: 0");
                    reLoadImage(elemId, data);
                    rowData['comparisonImgSrc'] = data;
                } else {
                    layer.msg(res.message)
                }
                layui.layer.close(indexUploadImags);
            }
        });
    }

    function reLoadImage(elemId, value, valueId) {
        zmnUploadUtil.reLoadImage($, elemId, value, valueId);
        let next = $("#" + elemId + "-value").next();
        $("#" + elemId + "-values").attr("src",value).attr("style", "width: 0;height: 0");
        let next1 = $(next).next();
        $(next).attr("style", "visibility:hidden !important");
        $(next1).attr("style", "visibility:hidden !important");
    }

    function initClickEvent() {
        // 点击删除图片
        $(".btn-delete").off('click');
        $(document).on('click', '.btn-delete', function () {
            let $uploadDiv = $(this).parent().prev().prev();
            $uploadDiv.attr("style", "");
            $uploadDiv.find(".layui-upload-drag").attr("style", "");
            $uploadDiv.find("i").attr("style", "");
            $uploadDiv.find("p").attr("style", "");
            $uploadDiv.find(":hidden").val("");
            $uploadDiv.find("img").prop("src", "");
        });
        // 点击放大
        $(".btn-review").off('click');
        $(document).on('click', '.btn-review', function () {
            if (!$(this).parent().prev().prev().find("input").eq(0).val()) {
                layer.msg("请上传对应图片再预览");
                return;
            }
            let $container = $(this).parent().prev().prev().find("img").eq(0);
            $container.viewer().on('hide', function () {
                $container.viewer('destroy');
            });
            let index = $(this).index();
            $container.viewer('view', index);
        });
    }

    function initViewEvent() {
        // 点击放大
        $(".btn-review").off('click');
        $(document).on('click', '.btn-main-review', function () {
            if (!$(this).parent().prev().find("input").eq(0).val()) {
                layer.msg("请上传对应图片再预览");
                return;
            }
            let $container = $(this).parent().prev().find("img").eq(0);
            $container.viewer().on('hide', function () {
                $container.viewer('destroy');
            });
            let index = $(this).index();
            $container.viewer('view', index);
        });
    }


    // 程序入口
        function init() {
            // 初始化页面
            initPage();

            // 初始化事件
            initEvent();

        }


        // 初始化
        init();

        exports('oms_work_modify_part');
    }
);
